// Train the model!!
async function train() {
  updateUI('training');
  stopPlayer(playerMelody, document.getElementById('btnPlayMelody'));

  currentSample = null;
  trainingStep.textContent = 0;
  totalSteps.textContent = midime.config.epochs = parseInt(trainingSteps.value);

  const losses = [];

  await midime.train(training.z, async (epoch, logs) => {
    await mm.tf.nextFrame();
    trainingStep.textContent = epoch + 1;
    losses.push(logs.total);
    plotLoss(losses);
  });
  updateUI('training-done');
  sample();
}

async function play(event, playerIndex) {
  let player, mel;
  if (playerIndex === 0) player = playerInput;
  else if (playerIndex === 1) player = playerMelody;
  else if (playerIndex === 2) player = playerSample;

  if (playerIndex === 0) mel = input;
  else if (playerIndex === 1) mel = melody;
  else if (playerIndex === 2) mel = currentSample;

  const btn = event.target;
  if (player.isPlaying()) {
    stopPlayer(player, btn);
  } else {
    startPlayer(player, btn);
    player.loadSamples(mel).then(() => loopMelody(player, mel, btn))
  }
}
